$(function (){
    $("#sendCodeBtn").click(function (event){
        // 阻止表单默认提交
        event.preventDefault();
        const $sendCodeBtn = $("#sendCodeBtn")

        let email = $("#email").val();
        if (email === "") {
            alert("请输入邮箱地址");
            return;
        }
        $sendCodeBtn.prop("disabled", true)
        $sendCodeBtn.text("发送中...");
        startCountdown($sendCodeBtn);

        $.ajax({
            url: '/auth/send-captcha',
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify({email: email}),
            success: function (res){
                if(res.code === 200){
                    console.log(res);
                }else{
                    alert(res.message);
                }
            },
            error: function (xhr, status, error) {
            console.error("请求失败:", error);
        }
        })
    })

    $("#registerBtn").click(function (event){
        event.preventDefault();
        let email = $("#email").val();
        let captcha = $("#captcha").val();
        let password = $("#password").val();
        let password_confirm = $("#confirm-password").val();
        if (email === "" || captcha === "" || password === "" || password_confirm === "")
            alert("请输入完整信息");
        if (password !== password_confirm) {
            alert("两次输入的密码不一致");
            return;
        }
        let data = {
            email: email,
            captcha: captcha,
            password: password,
            password_confirm: password_confirm
        }

        $.ajax({
            url: '/auth/register',
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(data),
            success: function (res){
                if(res.code === 200){
                    window.location.href = '/auth/login';
                    console.log(res);
                }else{
                    alert(res.message);
                }
            },
            error: function (xhr, status, error) {
            console.error("请求失败:", error);
        }
        })


    })
})

// 倒计时功能
function startCountdown(button) {
    let countdown = 60; // 倒计时 60 秒
    button.text(`重新发送(${countdown}s)`);

    let timer = setInterval(function() {
        countdown--;
        button.text(`重新发送(${countdown}s)`);

        if (countdown <= 0) {
            clearInterval(timer);
            button.prop("disabled", false)
            button.text("发送验证码");
        }
    }, 1000); // 每秒更新一次
}

